#include "list.h"
#include "hash.h"
#include <string.h>
struct my_data {
    int age;
    char name[20];
    struct hlist_node hnode; 
};

unsigned int get_key(const char *name) 
{
    
    unsigned int key = 0;

    while(*name) {
        key += *name;
        name++;
    }
    return key;
}


int main(void)
{
    DEFINE_HASHTABLE(my_hash, 5); //  定义一个空的哈希表
    
   
    struct my_data stu[] = {
        {18, "Tom"},
        {19, "Jack"},
        {20, "Jack"},
        {30, "Zhangsan"},
        {100, "Lisi"},
        {40, "Songxiaobao"},
    };
    
    for(int i = 0; i < sizeof(stu) / sizeof(*stu); ++i)
        hash_add(my_hash, &stu[i].hnode, get_key(stu[i].name));	  // 头插	
     
   
    struct my_data  *cur; 
    struct hlist_node *next;
    unsigned bkt;
    
    // 遍历整个哈希表
    printf("遍历整个哈希表:\n");
    hash_for_each(my_hash, bkt, cur, hnode) {	
		printf("bkt = %d, %s\n", bkt, cur->name); 
    }

    // 遍历某个桶
    printf("遍历某个桶:\n");
    hash_for_each_possible(my_hash, cur, hnode, get_key("Jack")) {	
        printf("name = %s, age = %d\n", cur->name, cur->age); 
    }
    
    printf("安全遍历某个桶并删除:\n");

    hash_for_each_possible_safe(my_hash, cur, next, hnode, get_key("Jack")) {	
        printf("删除 %s\n",  cur->name); 
        hlist_del(&cur->hnode);
        
    }
    
    printf("再次遍历整个哈希表:\n");
    hash_for_each(my_hash, bkt, cur, hnode) {	
		printf("bkt = %d, %s\n", bkt, cur->name); 
    }
    

    printf("安全遍历整个哈希表并删除:\n");
    hash_for_each_safe(my_hash, bkt, next, cur, hnode) {
        printf("删除 %s\n",  cur->name); 
        hlist_del(&cur->hnode); // 删除
        
    }
    
    if(hash_empty(my_hash)) {
        printf("my_hash is empty\n");
    }
    
    return 0;
}

